/**
 * created by 小卷毛, 2020/9/15
 * Copyright (c) 2020, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.sgcc.pda.mdrh.task.safe.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.sgcc.pda.lib_tools_database.bean.ControlProcess;
import com.sgcc.pda.lib_tools_database.bean.MeasureRelation;
import com.sgcc.pda.lib_tools_database.bean.MeasureRisk;
import com.sgcc.pda.lib_tools_database.bean.MeasureSummary;
import com.sgcc.pda.lib_tools_database.bean.RiskPointMeasure;
import com.sgcc.pda.lib_tools_database.bean.TypicalExp;
import com.sgcc.pda.lib_tools_database.bean.VideoStandard;
import com.sgcc.pda.lib_tools_database.bean.WorkContent;
import com.sgcc.pda.lib_tools_database.bean.other.RiskHttpState;
import com.sgcc.pda.lib_tools_database.bean.other.TicketMeasureSave;
import com.sgcc.pda.lib_tools_database.bean.other.VersionItem;
import com.sgcc.pda.lib_tools_database.bean.ticket.LocalImage;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketDetail;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketForType;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketMeeting;
import com.sgcc.pda.lib_tools_database.bean.ticket.TicketPermit;
import com.sgcc.pda.lib_tools_database.factory.ControlProcessImpl;
import com.sgcc.pda.lib_tools_database.factory.LocalImageImpl;
import com.sgcc.pda.lib_tools_database.factory.MeasureRelationImpl;
import com.sgcc.pda.lib_tools_database.factory.MeasureRiskImpl;
import com.sgcc.pda.lib_tools_database.factory.MeasureSummaryImpl;
import com.sgcc.pda.lib_tools_database.factory.RiskHttpStateImpl;
import com.sgcc.pda.lib_tools_database.factory.RiskPointMeasureImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketDetailImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketForTypeImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketMeasureSaveImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketMeetingImpl;
import com.sgcc.pda.lib_tools_database.factory.TicketPermitImpl;
import com.sgcc.pda.lib_tools_database.factory.TypicalExpImpl;
import com.sgcc.pda.lib_tools_database.factory.VideoStandardImpl;
import com.sgcc.pda.lib_tools_database.factory.WorkContentImpl;
import com.sgcc.pda.lib_tools_database.gen.LocalImageDao;
import com.sgcc.pda.lib_tools_database.gen.TicketDetailDao;
import com.sgcc.pda.lib_tools_database.gen.TicketPermitDao;
import com.sgcc.pda.lib_tools_database.util.InputParam;
import com.sgcc.pda.mdrh.task.safe.entity.TicketDetailResult;
import com.sgcc.pda.mdrh.task.safe.entity.TicketSaveInfo;
import com.sgcc.pda.mdrh.task.safe.entity.VersionCheckResult;
import com.sgcc.pda.mdrh.task.safe.oss.OSSHelper;
import com.sgcc.pda.mdrh.task.safe.oss.OnOSSDownloadListener;
import com.sgcc.pda.mdrh.task.safe.oss.OnOSSStatusListener;
import com.sgcc.pda.mdrh.task.safe.util.HttpUtil;
import com.sgcc.pda.mdrh.zoom.router.BaseOperateRouter;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;
import com.sgcc.pda.tools.JsonUtils;
import com.sgcc.pda.tools.SPUtils;
import com.sgcc.pda.web.impl.HttpCallbackInterface;
import com.sgcc.pda.web.service.ZoomWebControler;

import org.greenrobot.greendao.Property;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描 述：数据库、离线数据更新服务
 * 作 者：小卷毛  2020-09-15 17:41
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
public class BaseCheckService extends Service {

    private Timer mTimeStampTimer;
    private TimerTask mTimerTask; //检查更新任务
    private TimerTask mLoginTask; //登录状态任务

    private TimerTask mLocalTicketTask; //离线工作票任务
    private TimerTask mLocalUploadTask; //离线上传任务

    // 线程池（数据库更新）
    private ExecutorService cachedThreadPool = Executors.newFixedThreadPool(2);
    // 离线操作线程池（工作票、班前会）
    private ExecutorService offLineThreadPool = Executors.newFixedThreadPool(3);

    private final IBinder binder = new TimerBinder(); //绑定器

    @SuppressWarnings("InnerClassMayBeStatic")
    public class TimerBinder extends Binder { }

    @Override
    public void onCreate() {
        super.onCreate();
        registerNetwork();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (mTimeStampTimer == null)
            mTimeStampTimer = new Timer();

        checkLoginState();
        return binder;
    }

    /**
     * 判断登录状态（每隔3s检查一次登录状态）
     */
    private void checkLoginState() {
        mLoginTask = new TimerTask() {
            @Override
            public void run() {
                // 用户uid
                String uid = SharepreferenceUtil.getUid(BaseCheckService.this);
                // 加密模式
                String mode = SharepreferenceUtil.getEncryptionMode(BaseCheckService.this);

                if (!TextUtils.isEmpty(uid)
                        && !TextUtils.isEmpty(mode)) {
                    // 执行版本检查
                    if (mTimerTask == null) {
                        initTimer();

                        // 执行定时数据库同步任务，每20分钟触发一次
                        mTimeStampTimer.schedule(mTimerTask, 3 * 1000, 20 * 60 * 1000);
                    }

                    // 执行离线工作票任务
                    if (mLocalTicketTask == null) {
                        initLocalTimer();

                        // 执行定时工作票任务，每3分钟触发一次
                        mTimeStampTimer.schedule(mLocalTicketTask, 500, 3 * 60 * 1000);
                        // 执行定时上传任务，每分钟触发一次
                        mTimeStampTimer.schedule(mLocalUploadTask, 200, 60 * 1000);
                    }

                    Log.i("login", "当前用户已登录");
                } else {
                    // 取消所有任务
                    if (mTimerTask != null) {
                        mTimerTask.cancel();
                        mTimerTask = null;
                    }

                    if (mLocalTicketTask != null) {
                        mLocalTicketTask.cancel();
                        mLocalTicketTask = null;
                    }

                    if (mLocalUploadTask != null) {
                        mLocalUploadTask.cancel();
                        mLocalUploadTask = null;
                    }

                    Log.e("login", "当前用户未登录");
                }
            }
        };

        mTimeStampTimer.schedule(mLoginTask, 2 * 1000, 3 * 1000);
    }

    /**
     * 初始化定时任务
     */
    private void initTimer() {
        // 版本检查任务
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                getCheckData();
                // 获取设施列表
                getTicketFaciTypes();
            }
        };
    }

    /**
     * 初始化离线定时任务
     */
    private void initLocalTimer() {
        // 拉取工作票详情
        mLocalTicketTask = new TimerTask() {
            @Override
            public void run() {
                getTicketDetail();
            }
        };

        // 上传附件和数据
        mLocalUploadTask = new TimerTask() {
            @Override
            public void run() {
                checkUploadMode();
            }
        };
    }

    /**
     * 数据库版本号检查
     */
    private void getCheckData() {
        HttpUtil.getVersonData(
                this,
                new HttpCallbackInterface() {
                    @Override
                    public void httpSuccess(String result) {
                        Log.i("onSuccess", result);
                        try {
                            // 解析数据
                            VersionCheckResult data = JsonUtils.toBean(result, VersionCheckResult.class);

                            if (data != null
                                    && data.getDTS() != null
                                    && !data.getDTS().isEmpty()) {
                                updateData(data.getDTS());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void httpFailed(int errorCode, String errorMsg) {
                        Log.e("onFail-version", errorCode + "：" + errorMsg);
                    }
                });
    }

    /**
     * 下载数据库数据
     *
     * @param list 待下载数据库版本
     */
    private void updateData(List<VersionItem> list) {
        for (final VersionItem item : list) {
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    HttpUtil.updateVersonDataSync(
                            BaseCheckService.this,
                            item,
                            new HttpCallbackInterface() {
                                @Override
                                public void httpSuccess(String result) {
                                    try {
                                        JSONObject obj = new JSONObject(result);
                                        if (obj.has("RT_F")
                                                && "1".equals(obj.optString("RT_F"))) {
                                            String array = obj.optString("DTS");

                                            if (!TextUtils.isEmpty(array)) {
                                                switch (item.getTableName()) {
                                                    case "KN_SEC_CTL_PROC":
                                                        new ControlProcessImpl()
                                                                .insertList(JsonUtils.toList(array, ControlProcess.class));
                                                        break;
                                                    case "KN_MEASURE_RISK":
                                                        new MeasureRiskImpl()
                                                                .insertList(JsonUtils.toList(array, MeasureRisk.class));
                                                        break;
                                                    case "KN_REL_MEASURE_PROC":
                                                        new MeasureRelationImpl()
                                                                .insertList(JsonUtils.toList(array, MeasureRelation.class));
                                                        break;
                                                    case "KN_MEASURE_SUMMARY":
                                                        new MeasureSummaryImpl()
                                                                .insertList(JsonUtils.toList(array, MeasureSummary.class));
                                                        break;
                                                    case "KN_RISK_POINT_MEASURE":
                                                        new RiskPointMeasureImpl()
                                                                .insertList(JsonUtils.toList(array, RiskPointMeasure.class));
                                                        break;
                                                    case "KN_TYPICAL_EXP":
                                                        new TypicalExpImpl()
                                                                .insertList(JsonUtils.toList(array, TypicalExp.class));
                                                        break;
                                                    case "KN_STAN_VIDEO":
                                                        new VideoStandardImpl()
                                                                .insertList(JsonUtils.toList(array, VideoStandard.class));
                                                        break;
                                                    case "KN_WORK_CONTENT":
                                                        new WorkContentImpl()
                                                                .insertList(JsonUtils.toList(array, WorkContent.class));
                                                        break;
                                                }
                                            }

                                            new InputParam().saveParam(item);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void httpFailed(int errorCode, String errorMsg) {
                                    Log.e("onFail-database", errorCode + "：" + errorMsg);
                                }
                            });
                }
            });
        }
    }

    /**
     * 获取工作票类型与设施关系表
     */
    private void getTicketFaciTypes() {
        HttpUtil.getTicketFaciTypes(
                this,
                new HttpCallbackInterface() {
                    @Override
                    public void httpSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            if (obj.has("RT_F")
                                    && "1".equals(obj.optString("RT_F"))) {
                                String array = obj.optString("DTS");
                                if (!TextUtils.isEmpty(array)) {
                                    // 保存本地数据库
                                    new TicketForTypeImpl()
                                            .insertList(JsonUtils.toList(array, TicketForType.class));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void httpFailed(int errorCode, String errorMsg) {
                        Log.e("onFail-Faci", errorCode + "：" + errorMsg);
                    }
                }
        );
    }

    /**
     * 登录获取待许可、待终结工作票信息
     */
    private void getTicketDetail() {
        HttpUtil.getLocalTicketDetail(
                this,
                new HttpCallbackInterface() {
                    @Override
                    public void httpSuccess(String result) {
                        try {
                            // 解析数据
                            TicketDetailResult data = JsonUtils.toBean(result, TicketDetailResult.class);

                            // 数据获取成功且有值
                            if (data != null
                                    && "1".equals(data.getRT_F())
                                    && data.getDTS() != null
                                    && !data.getDTS().isEmpty()) {
                                Log.i("tiketDetail", data.getDTS().size() + "");

                                // 当前用户ID
                                String userId =
                                        SharepreferenceUtil
                                                .getUid(BaseCheckService.this);

                                // 插入数据库
                                new TicketDetailImpl().insertList(data.getDTS(), userId);
                            }

                            // 下载网络图片
                            downloadImage();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void httpFailed(int errorCode, String errorMsg) {
                        Log.e("onFail-ticket:", errorCode + "：" + errorMsg);
                    }
                }
        );
    }

    /**
     * 下载待终结网络图片
     */
    private void downloadImage() {
        // 查询待下载的图片列表
        final List<LocalImage> imageList = new LocalImageImpl().findByParam(
                new Property[]{LocalImageDao.Properties.AttachStatus},
                new String[]{"03"}
        );

        Log.i("downloadImage", imageList == null ? "0" : imageList.size() + "");

        // 下载图片
        if (imageList != null && imageList.size() > 0) {
            // 阿里云网络路径集合
            final ArrayList<LocalImage> ossImgs = new ArrayList<>();

            for (final LocalImage item : imageList) {
                if (item.getAttachSrc().contains("oss")) ossImgs.add(item);
                else {
                    // 本地保存目录
                    File pictureFolder = Environment.getExternalStorageDirectory();
                    // 第二个参数为你想要保存的目录名称
                    File appDir = new File(pictureFolder, "yxgkzy/image");
                    // 文件名称
                    String fileName = System.currentTimeMillis() + ".jpg";

                    ZoomWebControler.getInstance()
                            .downloadFile(
                                    this,
                                    0,
                                    item.getAttachSrc(),
                                    appDir.getAbsolutePath(),
                                    fileName,
                                    new BaseOperateRouter.CompleteListener() {
                                        @Override
                                        public void complete(int retCode, String result) {
                                            if (retCode == 1) {
                                                // 更新本地数据
                                                item.setAttachLocal(result);
                                                item.setAttachStatus("04");
                                                new LocalImageImpl().updateData(item);

                                                // 查询本地工作票
                                                TicketDetail data = new TicketDetailImpl().findData(
                                                        TicketDetailDao.Properties.RECORD_ID,
                                                        item.getParentId()
                                                );

                                                // 更新附件地址
                                                if ("1".equals(item.getAttachMode())
                                                        && "07".equals(item.getWtPersonType()))
                                                    data.setATTACH_SRC(result);

                                                // 更新附件地址
                                                if ("1".equals(item.getAttachMode())
                                                        && "03".equals(item.getWtPersonType()))
                                                    data.setWT_ATTACH_SRC(result);

                                                // 更新本地工作票信息
                                                new TicketDetailImpl().update(data);
                                            }
                                        }
                                    }
                            );
                }
            }

            // 阿里云下载图片
            if (!ossImgs.isEmpty()) {
                ArrayList<String> imgs = new ArrayList<>();

                for (LocalImage item : ossImgs)
                    imgs.add(item.getAttachSrc());

                OSSHelper.getInstance()
                        .downloadImages(
                                imgs,
                                new OnOSSDownloadListener() {
                                    @Override
                                    public void onDownloadSuccess(GetObjectResult result, int index) {
                                        if (result != null) {
                                            // 更新本地数据
                                            LocalImage item = ossImgs.get(index);
                                            item.setAttachLocal(
                                                    result.getResponseHeader().get("url"));
                                            item.setAttachStatus("04");
                                            new LocalImageImpl().updateData(item);

                                            // 查询本地工作票
                                            TicketDetail data = new TicketDetailImpl().findData(
                                                    TicketDetailDao.Properties.RECORD_ID,
                                                    item.getParentId()
                                            );

                                            // 更新附件地址
                                            if ("1".equals(item.getAttachMode())
                                                    && "07".equals(item.getWtPersonType()))
                                                data.setATTACH_SRC(item.getAttachLocal());

                                            // 更新附件地址
                                            if ("1".equals(item.getAttachMode())
                                                    && "03".equals(item.getWtPersonType()))
                                                data.setWT_ATTACH_SRC(item.getAttachLocal());

                                            // 更新本地工作票信息
                                            new TicketDetailImpl().update(data);
                                        }
                                    }
                                }
                        );
            }
        }
    }

    /**
     * 上传离线图片信息
     */
    private void uploadImage() {
        // 查询待上传的图片列表
        final List<LocalImage> imageList = new LocalImageImpl().findByParam(
                new Property[]{LocalImageDao.Properties.AttachStatus},
                new String[]{"01"},
                LocalImageDao.Properties.AttachMode
        );

        Log.i("uploadImage", imageList == null ? "0" : imageList.size() + "");

        // 上传图片
        if (imageList != null && imageList.size() > 0) {
            // 查询图片上传方式
            String model = SPUtils.get("upload-mode", "");

            if ("02".equals(model)) { //图片上传至阿里云
                ArrayList<String> images = new ArrayList<>();
                for (LocalImage item : imageList) images.add(item.getAttachSrc());

                OSSHelper.getInstance()
                        .uploadImages(
                                images,
                                new OnOSSStatusListener() {
                                    @Override
                                    public void onSuccess(PutObjectResult result, int index) {
                                        if (result != null) {
                                            // 更新本地数据
                                            LocalImage inner = imageList.get(index);
                                            inner.setAttachStatus("02"); //已上传
                                            inner.setAttachLocal(inner.getAttachSrc());
                                            inner.setAttachSrc(result.getResponseHeader().get("url"));
                                            new LocalImageImpl().updateData(inner);
                                        } else {
                                            if (index == imageList.size()) {
                                                submitTicketPermit();
                                            }
                                        }
                                    }
                                }
                        );
            } else { //图片上传至服务器
                final int[] currentSize = {0, 0};
                for (LocalImage item : imageList) {
                    try {
                        offLineThreadPool.execute(
                                ZoomWebControler.getInstance()
                                        .getBlockUploadFile(
                                                item.getAttachSrc(),
                                                "/weblogic/app/yxgkzy/image/",
                                                false,
                                                item,
                                                new ZoomWebControler.StatusListener() {
                                                    @Override
                                                    public void complete(int retCode, Object extra, String result) {
                                                        switch (retCode) {
                                                            case 0:
                                                                currentSize[0]++;
                                                                break;
                                                            case 1:
                                                                currentSize[0]++;
                                                                currentSize[1]++;

                                                                try {
                                                                    // 更新本地数据
                                                                    JSONObject obj = new JSONObject(result);
                                                                    LocalImage inner = (LocalImage) extra;
                                                                    inner.setAttachStatus("02"); //已上传
                                                                    inner.setAttachLocal(inner.getAttachSrc());
                                                                    inner.setAttachSrc(obj.optString("filePath"));
                                                                    new LocalImageImpl().updateData(inner);
                                                                } catch (JSONException e) {
                                                                    e.printStackTrace();
                                                                }
                                                                break;
                                                        }

                                                        // 是否全部提交完成
                                                        if (currentSize[0] == imageList.size()) {
                                                            if (currentSize[0] == currentSize[1]) {
                                                                submitTicketPermit();
                                                            }
                                                        }
                                                    }
                                                }
                                        )
                        );
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            submitTicketPermit();
        }
    }

    /**
     * 上传工作票许可信息
     */
    private void submitTicketPermit() {
        // 查询未上传图片的数量
        int count = new LocalImageImpl().queryCount(
                LocalImageDao.Properties.AttachStatus, "01");

        // 判断图片是否上传完成
        if (count == 0) {
            // 查询许可待提交数据列表
            final List<TicketPermit> list = new TicketPermitImpl().findByParam(
                    new Property[]{
                            TicketPermitDao.Properties.WT_IS_PERMIT,
                            TicketPermitDao.Properties.WT_MODE
                    },
                    new String[]{"0", "1"}
            );

            Log.i("submitPermit", list == null ? "0" : list.size() + "");

            // 上传待许可信息
            if (list != null && list.size() > 0) {
                final int[] currentSize = {0, 0};
                for (final TicketPermit item : list) {
                    offLineThreadPool.execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    HttpUtil.submitTicketPermitSync(
                                            BaseCheckService.this,
                                            item,
                                            new HttpCallbackInterface() {
                                                @Override
                                                public void httpSuccess(String result) {
                                                    currentSize[0]++;
                                                    currentSize[1]++;

                                                    item.setWT_IS_PERMIT("1");
                                                    new TicketPermitImpl().insert(item);

                                                    // 是否全部提交完成
                                                    if (currentSize[0] == list.size()) {
                                                        if (currentSize[0] == currentSize[1]) {
                                                            submitMeetingEnd();
                                                        }
                                                    }

                                                    Log.e("onSuccess-permit:", "许可数据提交成功！");
                                                }

                                                @Override
                                                public void httpFailed(int errorCode, String errorMsg) {
                                                    currentSize[0]++;

                                                    Log.e("onFail-permit:", errorCode + "：" + errorMsg);
                                                }
                                            }
                                    );
                                }
                            }
                    );
                }
            } else {
                submitMeetingEnd();
            }
        }
    }

    /**
     * 上传班前会结束信息
     */
    private void submitMeetingEnd() {
        // 查询未许可提交数量
        int count = new TicketPermitImpl().queryCount("1");

        // 判断许可信息是否提交完成
        if (count == 0) {
            // 查询待提交班前会信息
            final List<TicketMeeting> list = new TicketMeetingImpl().findDataAll();

            Log.i("submitMeeting", list == null ? "0" : list.size() + "");

            // 上传班前会信息
            if (list != null && list.size() > 0) {
                final int[] currentSize = {0, 0};
                for (final TicketMeeting item : list) {
                    offLineThreadPool.execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    HttpUtil.submitMeetingEndSync(
                                            BaseCheckService.this,
                                            item,
                                            new HttpCallbackInterface() {
                                                @Override
                                                public void httpSuccess(String result) {
                                                    currentSize[0]++;
                                                    currentSize[1]++;

                                                    // 删除本地数据
                                                    new TicketMeetingImpl().delete(item);

                                                    // 是否全部提交完成
                                                    if (currentSize[0] == list.size()) {
                                                        if (currentSize[0] == currentSize[1]) {
                                                            submitRiskSave();
                                                        }
                                                    }

                                                    Log.e("onSuccess-meeting:", "班前会数据提交成功！");
                                                }

                                                @Override
                                                public void httpFailed(int errorCode, String errorMsg) {
                                                    currentSize[0]++;

                                                    Log.e("onFail-meeting:", errorCode + "：" + errorMsg);
                                                }
                                            }
                                    );
                                }
                            }
                    );
                }
            } else {
                submitRiskSave();
            }
        }
    }

    /**
     * 上传知识库风险点取证信息
     */
    private void submitRiskSave() {
        // 查询班前会待提交数量
        int count = new TicketMeetingImpl().queryCount();

        // 判断班前会信息是否提交完成
        if (count == 0) {
            // 查询待提交风险点信息
            final List<RiskHttpState> list = new RiskHttpStateImpl().findDataAll();

            Log.i("submitRisk", list == null ? "0" : list.size() + "");

            // 上传风险点信息
            if (list != null && list.size() > 0) {
                final int[] currentSize = {0, 0}; //记录上传成功或是被次数
                for (final RiskHttpState item : list) {
                    offLineThreadPool.execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    String[] ids = item.getContent().split(",");
                                    List<TicketMeasureSave> saveList =
                                            new TicketMeasureSaveImpl().findRiskList(ids[0], ids[1], ids[2]);

                                    TicketSaveInfo info = new TicketSaveInfo();
                                    info.setAppNo(ids[0]);
                                    info.setPlanNo(ids[1]);
                                    info.setWtNo(ids[2]);

                                    // 循环遍历赋值，并判断是否上传完图片
                                    info.setIsChk("1");
                                    for (TicketMeasureSave item : saveList) {
                                        if (item.getRiskPoints().isEmpty())
                                            info.setIsChk("0");
                                    }
                                    info.setMeasures(saveList);

                                    HttpUtil.saveTicketRiskRecord(
                                            BaseCheckService.this,
                                            info.getAppNo(),
                                            info.getPlanNo(),
                                            info.getWtNo(),
                                            info.getIsChk(),
                                            JsonUtils.toJson(info.getMeasures()),
                                            new HttpCallbackInterface() {
                                                @Override
                                                public void httpSuccess(String result) {
                                                    currentSize[0]++;
                                                    currentSize[1]++;

                                                    // 删除本地数据
                                                    new RiskHttpStateImpl().delete(item);

                                                    // 是否全部提交完成
                                                    if (currentSize[0] == list.size()) {
                                                        if (currentSize[0] == currentSize[1]) {
                                                            submitTicketEnd();
                                                        }
                                                    }

                                                    Log.e("onSuccess-risk:", "风险点数据提交成功！");
                                                }

                                                @Override
                                                public void httpFailed(int errorCode, String errorMsg) {
                                                    currentSize[0]++;

                                                    Log.e("onFail-risk", errorCode + "：" + errorMsg);
                                                }
                                            }
                                    );
                                }
                            }
                    );
                }
            } else {
                submitTicketEnd();
            }
        }
    }

    /**
     * 上传终结工作票信息
     */
    private void submitTicketEnd() {
        // 查询风险点待提交数量
        int count = new RiskHttpStateImpl().queryCount();

        // 判断风险点信息是否提交完成
        if (count == 0) {
            // 查询终结待提交数据列表
            List<TicketPermit> list = new TicketPermitImpl().findByParam(
                    new Property[]{
                            TicketPermitDao.Properties.WT_IS_PERMIT,
                            TicketPermitDao.Properties.WT_MODE
                    },
                    new String[]{"0", "2"}
            );

            Log.i("submitEnd", list == null ? "0" : list.size() + "");

            // 上传终结数据
            if (list != null && list.size() > 0) {
                for (final TicketPermit item : list) {
                    offLineThreadPool.execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    HttpUtil.submitTicketEndSync(
                                            BaseCheckService.this,
                                            item,
                                            new HttpCallbackInterface() {
                                                @Override
                                                public void httpSuccess(String result) {
                                                    // 删除工作票
                                                    new TicketDetailImpl().deleteById(item.getRECORD_ID());
                                                    // 删除提交数据
                                                    new TicketPermitImpl().deleteById(item.getRECORD_ID());

                                                    Log.e("onSuccess-end:", "终结数据提交成功！");
                                                }

                                                @Override
                                                public void httpFailed(int errorCode, String errorMsg) {
                                                    Log.e("onFail-end:", errorCode + "：" + errorMsg);
                                                }
                                            }
                                    );
                                }
                            }
                    );
                }
            }
        }
    }

    /**
     * 监听网络连接状态
     */
    private void registerNetwork() {
        NetworkManager.getInstance()
                .registerNetwork(
                        this,
                        new NetworkManager.INetworkListener() {
                            @Override
                            public void connnect() {
                                // 用户uid
                                String uid = SharepreferenceUtil.getUid(BaseCheckService.this);
                                // 加密模式
                                String mode = SharepreferenceUtil.getEncryptionMode(BaseCheckService.this);

                                if (!TextUtils.isEmpty(uid)
                                        && !TextUtils.isEmpty(mode)) {
                                    // 执行离线上传任务
                                    if (mLocalUploadTask == null) {
                                        mLocalUploadTask = new TimerTask() {
                                            @Override
                                            public void run() {
                                                uploadImage();
                                            }
                                        };

                                        mTimeStampTimer.schedule(mLocalUploadTask, 1000, 60 * 1000);
                                    }
                                }
                            }

                            @Override
                            public void disconnect() {
                                // 取消离线上传任务
                                if (mLocalUploadTask != null) {
                                    mLocalUploadTask.cancel();
                                    mLocalUploadTask = null;
                                }
                            }
                        }
                );
    }

    /**
     * 判断图片上传方式
     */
    private void checkUploadMode() {
        String model = SPUtils.get("upload-mode", "");
        if (TextUtils.isEmpty(model)) {
            // 检查附件上传方式（阿里云或服务器）
            HttpUtil.getOSSToken(
                    this,
                    new HttpCallbackInterface() {
                        @Override
                        public void httpSuccess(String result) {
                            try {
                                JSONObject obj = new JSONObject(result);
                                if (obj.has("RT_F")
                                        && "1".equals(obj.optString("RT_F"))) {
                                    JSONObject jsonObj = obj.optJSONObject("DTS");

                                    if (jsonObj != null
                                            && jsonObj.has("uploadWay")) {
                                        SPUtils.put("upload-mode", jsonObj.optString("uploadWay"));
                                    }
                                }

                                uploadImage();
                            } catch (JSONException e) {
                                e.printStackTrace();
                                uploadImage();
                            }
                        }

                        @Override
                        public void httpFailed(int errorCode, String errorMsg) {
                            Log.e("onFail-uploadMode:", errorCode + "：" + errorMsg);
                            uploadImage();
                        }
                    }
            );
        } else {
            uploadImage(); //上传附件
        }
    }

    @Override
    public void onDestroy() {
        // 取消版本检查任务
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

        // 取消本地工作票任务
        if (mLocalTicketTask != null) {
            mLocalTicketTask.cancel();
            mLocalTicketTask = null;
        }

        // 取消离线上传任务
        if (mLocalUploadTask != null) {
            mLocalUploadTask.cancel();
            mLocalUploadTask = null;
        }

        // 取消登录检查任务
        if (mLoginTask != null) {
            mLoginTask.cancel();
            mLoginTask = null;
        }

        // 取消定时器
        if (mTimeStampTimer != null) {
            mTimeStampTimer.cancel();
            mTimeStampTimer = null;
        }

        // 关闭线程池
        cachedThreadPool.shutdown();
        offLineThreadPool.shutdown();
        super.onDestroy();
    }

}
